'use client'
import React, { useState, useEffect } from 'react';
import { Calendar, User, Tag, Upload, Plus, X } from 'lucide-react';
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from './ui/card';
import { Input } from './ui/input';
import { Textarea } from './ui/textarea';
import { Button } from './ui/button';
import TiptapEditor from './TiptapEditor';
import { Badge } from './ui/badge';
import { toast } from 'sonner';
import { createArticle, getArticleById, updateArticle } from '../services/articleService';
import { getCategories } from '../services/categoryService';
import { getTags } from '../services/tagService';
import { uploadCoverImage } from '../services/uploadService';
import { CreateArticleDto, UpdateArticleDto, Article } from '../types/article';
import { Category } from '../types/category';
import { Tag as TagType } from '../types/tag';

interface ArticleEditorProps {
  articleId?: number;
  onSaveSuccess?: (article: Article | null) => void;
}

const ArticleEditor: React.FC<ArticleEditorProps> = ({ articleId, onSaveSuccess }) => {
  const isEditMode = !!articleId;
  
  // 表单状态
  const [formData, setFormData] = useState<CreateArticleDto>({
    title: '',
    content: '',
    excerpt: '',
    coverImage: '',
    categoryId: 0,
    tagIds: [],
  });
  
  // 临时存储用户选择的图片文件，用于预览和提交时上传
  const [coverImageFile, setCoverImageFile] = useState<File | null>(null);
  // 本地预览URL
  const [previewUrl, setPreviewUrl] = useState<string>('');
  
  // 分类和标签数据
  const [categories, setCategories] = useState<Category[]>([]);
  const [tags, setTags] = useState<TagType[]>([]);
  const [selectedTags, setSelectedTags] = useState<number[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // 加载数据（分类、标签和可能的文章数据）
  useEffect(() => {
    const loadData = async () => {
      setIsLoading(true);
      try {
        // 并行加载分类和标签
        const [categoriesData, tagsData] = await Promise.all([
          getCategories(),
          getTags()
        ]);
        setCategories(categoriesData);
        setTags(tagsData);
        
        // 如果是编辑模式，加载文章数据
        if (isEditMode && articleId) {
          const article = await getArticleById(articleId, true);
          if (article) {
            // 填充表单数据
            setFormData({
              title: article.title || '',
              content: article.content || '',
              excerpt: article.excerpt || '',
              coverImage: article.coverImage || '',
              categoryId: article.categoryId || 0,
              tagIds: article.tags?.map(tag => tag.id) || []
            });
            
            // 设置已选标签
            setSelectedTags(article.tags?.map(tag => tag.id) || []);
            
            // 设置封面图片预览
            if (article.coverImage) {
              setPreviewUrl(article.coverImage);
            }
          }
        } else if (categoriesData.length > 0) {
          // 创建模式：如果有分类，默认选择第一个
          setFormData(prev => ({
            ...prev,
            categoryId: categoriesData[0].id
          }));
        }
      } catch (error) {
        toast.error('加载数据失败，请刷新页面重试');
        console.error('加载数据失败:', error);
      } finally {
        setIsLoading(false);
      }
    };
    
    loadData();
  }, [isEditMode, articleId]);

  // 处理表单输入变化
  const handleInputChange = (field: keyof CreateArticleDto, value: any) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 处理标签选择
  const handleTagToggle = (tagId: number) => {
    setSelectedTags(prev => {
      const newSelectedTags = prev.includes(tagId)
        ? prev.filter(id => id !== tagId)
        : [...prev, tagId];
      
      // 同步更新formData中的tagIds
      handleInputChange('tagIds', newSelectedTags);
      return newSelectedTags;
    });
  };

  // 处理封面图片选择（只存储文件和生成预览，不上传）
  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      // 存储文件对象
      setCoverImageFile(file);
      
      // 生成本地预览URL
      const objectUrl = URL.createObjectURL(file);
      setPreviewUrl(objectUrl);
      
      // 清除旧的预览URL
      return () => URL.revokeObjectURL(objectUrl);
    }
  };

  // 移除封面图片
  const removeCoverImage = () => {
    // 清除文件和预览
    setCoverImageFile(null);
    setPreviewUrl('');
    handleInputChange('coverImage', '');
  };

  // 自动生成摘要
  const generateExcerpt = () => {
    if (formData.content) {
      const excerpt = formData.content.substring(0, 150) + (formData.content.length > 150 ? '...' : '');
      handleInputChange('excerpt', excerpt);
    }
  };

  // 提交表单
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 表单验证
    if (!formData.title.trim()) {
      toast.error('请输入文章标题');
      return;
    }
    
    if (!formData.content.trim()) {
      toast.error('请输入文章内容');
      return;
    }
    
    if (formData.categoryId === 0) {
      toast.error('请选择文章分类');
      return;
    }

    setIsSubmitting(true);
    try {
      // 准备提交数据
      const submitData = {
        ...formData,
        tagIds: Array.isArray(formData.tagIds) ? formData.tagIds : []
      };
      
      // 如果有封面图片文件，先上传获取URL
      if (coverImageFile) {
        toast.info('正在上传封面图片...');
        const imageResponse = await uploadCoverImage(coverImageFile);
        submitData.coverImage = imageResponse.url;
      }
      
      let savedArticle: Article | null = null;
      
      if (isEditMode && articleId) {
        // 编辑模式：提交更新，编辑后重置isActive为-1（未审核）
        savedArticle = await updateArticle(articleId, { ...submitData, isActive: -1 } as UpdateArticleDto);
        toast.success('文章更新成功！文章已重新提交审核');
      } else {
        // 创建模式：提交新文章
        savedArticle = await createArticle(submitData);
        toast.success('文章创建成功！');
      }
      
      // 调用成功回调
      if (onSaveSuccess) {
        onSaveSuccess(savedArticle);
      }
    } catch (error: any) {
      // 显示更详细的错误信息
      const action = isEditMode ? '更新' : '创建';
      const errorMessage = error.response?.data?.message || error.message || `文章${action}失败，请重试`;
      toast.error(errorMessage);
      console.error(`文章${action}失败:`, error);
    } finally {
      setIsSubmitting(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex justify-center items-center h-64">
        <p className="text-lg text-gray-500">加载中...</p>
      </div>
    );
  }

  return (
    <Card className="mb-8">
      <form onSubmit={handleSubmit}>
        <CardHeader className="space-y-4">
          <CardTitle className="text-2xl">
            {isEditMode ? '编辑文章' : '发布新文章'}
          </CardTitle>
          
          {/* 文章标题 */}
          <div className="space-y-2">
            <label htmlFor="title" className="text-sm font-medium">
              文章标题 <span className="text-destructive">*</span>
            </label>
            <Input
              id="title"
              placeholder="请输入文章标题"
              value={formData.title}
              onChange={(e) => handleInputChange('title', e.target.value)}
              className="text-lg"
              required
            />
          </div>
        </CardHeader>
        
        <CardContent className="space-y-6">
          {/* 封面图片上传 */}
          <div className="space-y-2">
            <label className="text-sm font-medium">封面图片</label>
            <div className="border-2 border-dashed rounded-lg p-6 text-center">
              {previewUrl ? (
                <div className="relative">
                  <img 
                    src={previewUrl} 
                    alt="文章封面预览" 
                    className="max-h-48 object-cover rounded-lg mx-auto"
                  />
                  <Button
                    variant="destructive"
                    size="icon"
                    className="absolute -top-2 -right-2"
                    onClick={removeCoverImage}
                  >
                    <X size={16} />
                  </Button>
                </div>
              ) : (
                <label className="cursor-pointer">
                  <div className="flex flex-col items-center justify-center">
                    <Upload size={24} className="mb-2 text-muted-foreground" />
                    <p className="text-sm text-muted-foreground">点击上传封面图片</p>
                    <p className="text-xs text-muted-foreground mt-1">支持 JPG, PNG, GIF 格式</p>
                  </div>
                  <input 
                    type="file" 
                    accept="image/*" 
                    className="hidden" 
                    onChange={handleImageUpload}
                  />
                </label>
              )}
            </div>
          </div>
          
          {/* 文章分类 */}
          <div className="space-y-2">
            <label htmlFor="category" className="text-sm font-medium">
              文章分类 <span className="text-destructive">*</span>
            </label>
            <select
              id="category"
              value={formData.categoryId}
              onChange={(e) => handleInputChange('categoryId', parseInt(e.target.value))}
              className="w-full rounded-md border border-gray-300 px-3 py-2 bg-transparent text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-950 focus-visible:ring-offset-2"
              required
            >
              <option value="0" disabled>请选择分类</option>
              {categories.map(category => (
                <option key={category.id} value={category.id}>
                  {category.name}
                </option>
              ))}
            </select>
          </div>
          
          {/* 文章标签 */}
          <div className="space-y-2">
            <label className="text-sm font-medium">文章标签</label>
            <div className="flex flex-wrap gap-2">
              {tags.map(tag => (
                <Badge
                  key={tag.id}
                  variant={selectedTags.includes(tag.id) ? "default" : "outline"}
                  className={`cursor-pointer ${selectedTags.includes(tag.id) ? 'bg-primary text-white' : ''}`}
                  onClick={() => handleTagToggle(tag.id)}
                >
                  {tag.name}
                </Badge>
              ))}
            </div>
          </div>
          
          {/* 文章摘要 */}
          <div className="space-y-2">
            <div className="flex justify-between">
              <label htmlFor="excerpt" className="text-sm font-medium">文章摘要</label>
              <Button
                variant="ghost"
                size="sm"
                onClick={generateExcerpt}
                className="h-7 text-xs"
              >
                自动生成
              </Button>
            </div>
            <Textarea
              id="excerpt"
              placeholder="请输入文章摘要（可选）"
              value={formData.excerpt}
              onChange={(e) => handleInputChange('excerpt', e.target.value)}
              rows={3}
              maxLength={200}
            />
            <p className="text-xs text-muted-foreground text-right">
              {(formData.excerpt || '').length}/200
            </p>
          </div>
          
          {/* 文章内容 */}
          <div className="space-y-2">
            <label htmlFor="content" className="text-sm font-medium">
              文章内容 <span className="text-destructive">*</span>
            </label>
            <TiptapEditor
              value={formData.content}
              onChange={(html) => handleInputChange('content', html)}
            />
          </div>
        </CardContent>
        
        <CardFooter className="flex justify-end space-x-3 border-t pt-4">
          <Button
            type="button"
            variant="ghost"
            onClick={() => {
              if (onSaveSuccess) {
                onSaveSuccess(null); // 取消编辑
              }
            }}
            disabled={isSubmitting}
          >
            取消
          </Button>
          <Button
            type="submit"
            disabled={isSubmitting || isLoading}
          >
            {isSubmitting ? '提交中...' : (isEditMode ? '更新文章' : '发布文章')}
          </Button>
        </CardFooter>
      </form>
    </Card>
  );
};

export default ArticleEditor;